package com.example.ecommerce.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ecommerce.entity.UserRole;
import com.example.ecommerce.entity.Role;
import com.example.ecommerce.mapper.UserRoleMapper;
import com.example.ecommerce.service.UserRoleService;
import com.example.ecommerce.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Autowired
    private RoleService roleService;

    @Override
    public void assignRoles(Long userId, List<Long> roleIds) {
        // 删除原有关系
        deleteByUserId(userId);
        
        // 批量保存新关系
        if (roleIds != null && !roleIds.isEmpty()) {
            List<UserRole> userRoles = roleIds.stream()
                    .map(roleId -> {
                        UserRole userRole = new UserRole();
                        userRole.setUserId(userId);
                        userRole.setRoleId(roleId);
                        userRole.setCreatedAt(LocalDateTime.now());
                        userRole.setUpdatedAt(LocalDateTime.now());
                        return userRole;
                    })
                    .collect(Collectors.toList());
            saveBatch(userRoles);
        }
    }

    @Override
    public void deleteByUserId(Long userId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, userId);
        userRoleMapper.delete(wrapper);
    }

    @Override
    public void deleteByRoleId(Long roleId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getRoleId, roleId);
        userRoleMapper.delete(wrapper);
    }

    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, userId)
              .select(UserRole::getRoleId);
        
        return list(wrapper).stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
    }

    @Override
    public List<Long> getUserIdsByRoleId(Long roleId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getRoleId, roleId)
              .select(UserRole::getUserId);
        
        return list(wrapper).stream()
                .map(UserRole::getUserId)
                .collect(Collectors.toList());
    }

    @Override
    public boolean hasRole(Long userId, String roleCode) {
        // 获取用户的所有角色
        List<Long> roleIds = getRoleIdsByUserId(userId);
        if (roleIds.isEmpty()) {
            return false;
        }
        
        // 查询指定编码的角色
        LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
//        roleWrapper.eq(Role::getCode, roleCode)
        roleWrapper.eq(Role::getStatus, 1)
                  .in(Role::getId, roleIds);
        
        return roleService.count(roleWrapper) > 0;
    }

    @Override
    public boolean hasAnyRole(Long userId, List<String> roleCodes) {
        if (roleCodes == null || roleCodes.isEmpty()) {
            return false;
        }
        
        // 获取用户的所有角色
        List<Long> roleIds = getRoleIdsByUserId(userId);
        if (roleIds.isEmpty()) {
            return false;
        }
        
        // 查询是否有指定编码的角色
        LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
//        roleWrapper.in(Role::getCode, roleCodes)
        roleWrapper.eq(Role::getStatus, 1)
                  .in(Role::getId, roleIds);
        
        return roleService.count(roleWrapper) > 0;
    }
} 